package ninder.system.control;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.hibernate.exception.ConstraintViolationException;


import ninder.system.model.User;
import ninder.system.util.HibernateUtil;

public class UserManager {

	private static UserManager manager = null;
	
	
	
	public enum UserInfo {
		NAME("name"), EMAIL("email"), ID("id"), LOGIN("login"), PASSWORD(
				"password"), GENDER("gender"), ID_TYPE("idType");
		
		private String description;

		private UserInfo(final String description) {
			this.description = description;
		}

		public String getDescription() {
			return description;
		}
	}

	private UserManager() {

	}

	public static synchronized UserManager getInstance() {
		if (manager == null) {
			manager = new UserManager();
		}
		return manager;
	}

	public Integer createUser(User u) {

		return (Integer) HibernateUtil.create(u);
	}

	public void updateUser(User u) {

		HibernateUtil.update(u);
	}

	public void deleteUser(User u) {

		HibernateUtil.delete(u);
	}
	
	@SuppressWarnings("unchecked")
	public User getUser(String login)  {
		Collection<SimpleExpression> exps = new ArrayList<SimpleExpression>();
		exps.add(Restrictions.like("login", login));
		List<User> user = null;
		try {
			user = (List<User>) HibernateUtil.createQuery(User.class, exps);
			
		} catch (ConstraintViolationException e) {
			
		}

		return user.isEmpty() ? null : user.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers(long idClinical) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		List<User> result = session.createSQLQuery(
				"select " + "{u.*} " + "from User {u} where u.id_clincal="+idClinical+";").addEntity("u", User.class).list();
		session.getTransaction().commit();
		return result;
	}

	public String getUserInfo(String login, UserInfo info)  {
		if (getUser(login) != null){
			
		switch (info) {
		
		case ID_TYPE:
			return String.valueOf(getUser(login).getIdType());
		case NAME:
			return String.valueOf(getUser(login).getLogin());
		
		case ID:
			return String.valueOf(getUser(login).getId());
		case LOGIN:
			return getUser(login).getLogin();
		case PASSWORD:
			return getUser(login).getPassword();
		
		default:
			return new String();
		}
		
		}
		return null;
		}
}
